#ifndef TW_DIR_TOOL_HPP
#define TW_DIR_TOOL_HPP

#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <errno.h>
#include "TW_Log.hpp"

namespace TW_Dir
{
    #define DIR_NAME_ERROR              1
    #define DIR_PERMISSION_ERROR        2
    #define DIR_PARENT_NO_EXIST_ERROR   3
    #define DF_SPACE_NO_ENOUGH_ERROR    4
    #define FILESYSTEM_READ_ONLY        5

    TW_Log::Logger& log = TW_Log::Logger().getInstance();

    int tw_check_dir_name(char* v_path)
    {
        if(v_path == NULL) return -1;
        for(int i = 0; i < strlen(v_path); ++i)
        {
            if(v_path[i] >= '0' && v_path[i] <= '9') continue;
            else if(v_path[i] >= 'a' && v_path[i] <= 'z' || v_path[i] >= 'A' && v_path[i] <= 'Z') continue;
            else if(v_path[i] == '_' || v_path[i] == ' ' || v_path[i] == '-') continue;
            else return -1;
        }
        return 0;
    }

    int tw_create_multi_dir(char* v_path, unsigned int v_mask)
    {
        int checkRet = 0;
        char* delim = "/";
        char* subDir = "";

        subDir = strtok(v_path, delim);
        if(tw_check_dir_name(subDir) != 0) return DIR_NAME_ERROR;
        checkRet = mkdir(v_path, v_mask);

        while(subDir = strtok(NULL, delim))
        {
            checkRet = tw_create_dir(subDir, v_mask);
            if(checkRet != 0) return checkRet;
        }
        return 0;
    }

    int tw_create_dir(char* v_path, unsigned int v_mask)
    {
        if(tw_check_dir_name(v_path) != 0) return DIR_NAME_ERROR;

        int checkRet = 0;
        checkRet = mkdir(v_path, v_mask);

        if(checkRet == -1)
        {
            if(errno == EACCES) log(TW_Log::DEBUG, "test");
            if(errno == EEXIST);
        }

        return 0;
    }
}

#endif